//
//  SplashViewController.m
//  TestDemo
//
//  Created by a on 2022/11/21.
//

#import "SplashViewController.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import "SplashAdM.h"

@interface SplashViewController ()

@property (nonatomic,strong)SplashAdM * splashAM;

@end

@implementation SplashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.splashAM = [SplashAdM new];
}

- (IBAction)getIdfaClicked:(id)sender {
    [self getIdfa];
}

- (IBAction)loadAdButtonClicked:(id)sender {
    self.splashAM.autoShow = NO;
    [self.splashAM setupSplashAd:[self getKeyWindow]];
}

- (IBAction)showAdButtonClicked:(id)sender {
    self.splashAM.autoShow = YES;
    [self.splashAM setupSplashAd:[self getKeyWindow]];
}

- (void)getIdfa{
    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                NSLog(@"idfa=%@ 已经复制到您的粘贴板",idfa);
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = idfa;
            } else {
                     NSLog(@"请在设置-隐私-跟踪中允许App请求跟踪");
            }
        }];
    } else {
        // iOS14以下版本依然使用老方法
        // 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            NSLog(@"idfa=%@ 已经复制到您的粘贴板",idfa);
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = idfa;
        } else {
            NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
        }
    }
}

- (UIWindow *)getKeyWindow
{
    if (@available(iOS 13.0, *))
    {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
            {
                for (UIWindow *window in windowScene.windows)
                {
                    if (window.isKeyWindow)
                    {
                        return window;
                        break;
                    }
                }
            }
        }
    }
    else
    {
        return [UIApplication sharedApplication].keyWindow;
    }
    return nil;
}


- (void)dealloc{
    NSLog(@"splashViewController dealloc");
}

@end
